﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using TransitionEffects;

namespace SharpSoft.WPF
{
    public static class VisualHelper
    {
        /// <summary>
        /// 捕获UI元素的快照
        /// </summary>
        /// <param name="visual"></param>
        /// <returns></returns>
        public static RenderTargetBitmap Capture(UIElement visual)
        {
            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext ctx = dv.RenderOpen())
            {
                //这里使用BitmapCacheBrush理论上要比VisualBrush快不少，未实际测试所耗时间。
                //但是BitmapCacheBrush可能不支持UI元素的Clip、OpacityMask等特性，未实际测试。
                visual.CacheMode = new BitmapCache() { EnableClearType = true };
                BitmapCacheBrush vb = new BitmapCacheBrush(visual) { AutoLayoutContent = true, BitmapCache = new BitmapCache() { EnableClearType = true } };
                //VisualBrush vb = new VisualBrush(visual);
                ctx.DrawRectangle(vb, null,
                    new Rect(new Point(0, 0), visual.RenderSize));
            }
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)visual.RenderSize.Width, (int)visual.RenderSize.Height, 96, 96, PixelFormats.Default);
            bmp.Render(dv);
            bmp.Freeze();
            return bmp;
        }

        /// <summary>
        /// 查找指定类型的父级控件（返回第一个遇到的）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ui"></param>
        /// <returns></returns>
        public static T FindParent<T>(DependencyObject ui) where T : DependencyObject
        {
            if (ui == null)
            {
                return null;
            }
            DependencyObject parent = ui;
            do
            {
                parent = VisualTreeHelper.GetParent(parent);
            } while (parent != null && !(parent is T));
            return parent as T;
        }
        /// <summary>
        /// 查找指定类型的子集控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ui"></param>
        /// <returns></returns>
        public static T FindChild<T>(DependencyObject ui) where T : DependencyObject
        {
           var count= VisualTreeHelper.GetChildrenCount(ui);
            if (count>0)
            {
                for (int i = 0; i < count; i++)
                {
                   var child= VisualTreeHelper.GetChild(ui, i);
                    if (child is T ct)
                    {
                        return ct;
                    }
                    else if(child!=null)
                    {
                        var c = FindChild<T>(child);
                        if (c!=null)
                        {
                            return c;
                        }
                    }
                }
            }
            return null;
        }
    }
}
